/*
 * modbus.c
 *
 *  Created on: Nov 12, 2024
 *      Author: zxx
 */

#include "modbus.h"

uint8_t From_Flag = 0;

//uint8_t mOdbus_buffer[RX_SIZE];
MODBUS mymodbus;
uint16_t Reg[] ={
		0x0001,
		0x0002,
		0x0003,
		0x0004,
		0x0005,
		0x0006,
		0x0007,
};

uint8_t MODBUS_READ_RX(uint8_t *buf,uint8_t len)
{

	if(len > RX_SIZE)
	{
		len = RX_SIZE;
	}
	for(int i = 0;i < len;i ++)  		//拷贝接收到的数据到接收指针中
	{
		*buf = RX_BUFFER[i];  	//将数据复制到buf中
		buf  ++;
	}
	RX_SIZE = 0;
	return len;

}


void Modbus_Init()
{
	mymodbus.myadd = 0x01;

}


void Modbus_Func3()
{

	static int a = 0;
	if(Reg[a+1]=='\0')
	{
		a = 0;
	}
	Reg[a] +=2;
	a++;

	uint16_t Regadd,Reglen,crc;
	uint8_t i,j;

	//得到要读取寄存器的首地址
	Regadd = mymodbus.rcbuf[2]*256+mymodbus.rcbuf[3];
	//得到要读取寄存器的数据长度
	Reglen = mymodbus.rcbuf[4]*256+mymodbus.rcbuf[5];


	i = 0;
	mymodbus.sendbuf[i++] = mymodbus.myadd;
	mymodbus.sendbuf[i++] = 0x03;
	mymodbus.sendbuf[i++] = ((Reglen*2)%256);

	for(j=0;j<Reglen;j++)                    //返回数据
	{
		mymodbus.sendbuf[i++] = Reg[Regadd+j]/256;
		mymodbus.sendbuf[i++] = Reg[Regadd+j]%256;
	}
	crc = GetCRC16(mymodbus.sendbuf,i);
	mymodbus.sendbuf[i++] = crc/256;
	mymodbus.sendbuf[i++] = crc%256;

	uART_Send_Hex(mymodbus.sendbuf,i);//Hex数据发送
	//	uART_Send_String

}

void Modbus_Func6()
{

	uint16_t Regadd;
	uint16_t val;
	uint16_t i,crc;
	i = 0;
	Regadd=mymodbus.rcbuf[2]*256+mymodbus.rcbuf[3];  //得到要修改的地址
	val=mymodbus.rcbuf[4]*256+mymodbus.rcbuf[5];     //修改后的值
	Reg[Regadd]=val;  //修改本设备相应的寄存器
	//以下为回应主机
	mymodbus.sendbuf[i++]=mymodbus.myadd;//本设备地址
	mymodbus.sendbuf[i++]=0x06;        //功能码
	mymodbus.sendbuf[i++]=Regadd/256;
	mymodbus.sendbuf[i++]=Regadd%256;
	mymodbus.sendbuf[i++]=val/256;
	mymodbus.sendbuf[i++]=val%256;
	crc=GetCRC16(mymodbus.sendbuf,i);
	mymodbus.sendbuf[i++]=crc/256;  //
	mymodbus.sendbuf[i++]=crc%256;

	uART_Send_Hex(mymodbus.sendbuf,i);//Hex数据发送


}

void Modbus_Event()
{
	mymodbus.reflag = From_Flag;
	unsigned int crc;
	unsigned char crch,crcl;
	static unsigned char len;


	if(mymodbus.reflag)
	{
		From_Flag = 0;
		mymodbus.reflag= 0;
		len = MODBUS_READ_RX(mymodbus.rcbuf,MODBUS_BUFFSIZE);
		crc =  GetCRC16(mymodbus.rcbuf,len-2);
		crch = crc>>8;
		crcl = crc & 0xff;
		if((mymodbus.rcbuf[len-2] == crch) && (mymodbus.rcbuf[len-1] == crcl))//crc校验成功
		{


			if(mymodbus.rcbuf[0] == mymodbus.myadd)  // 检查地址是否时自己的地址
			{
				switch(mymodbus.rcbuf[1])   //分析mymodbus功能码
				{
				case 0:             break;
				case 1:             break;
				case 2:             break;
				case 3:       Modbus_Func3();   break;
				case 4:             break;
				case 5:             break;
				case 6:        Modbus_Func6();   	break;
				case 7:             break;
				case 8:             break;
				case 9:             break;
				}

			}

		}

	}

}




//void UartR






